import { Effect, Reducer, Subscription } from 'umi';
import http from '@/utils/http';

export interface ListType {
  id: number;
  name: string;
}

export interface IndexModelState {
  name: string;
  count: number;
  list: ListType[];
}

export interface IndexModelType {
  // 如果一个变量是一个不会变的字符串，可以直接拿这个字符串作为类型
  namespace: 'index';
  state: IndexModelState;
  effects: {
    query: Effect;
    load: Effect;
  };
  reducers: {
    save: Reducer;
    increment: Reducer;
    decrement: Reducer;
    add: Reducer;
    load2: Reducer;
  };
  subscriptions: { setup: Subscription };
}

// IndexModel仓库实例
const IndexModel: IndexModelType = {
  // 仓库的模块名
  namespace: 'index',

  // 仓库数据
  state: {
    name: '',
    count: 3,
    list: [],
  },

  // 写异步函数的，相当于vuex的actions
  effects: {
    *query({ payload }, { call, put }) {},
    *load({ payload }, { call, put }) {
      const res = yield call(http.get);
      yield put({
        type: 'load2',
        result: res.data,
      });
    },
  },

  // 写同步函数，用于改变state的值的，相当于vuex的mutations
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    increment(state, action) {
      return {
        ...state,
        count: state.count + 1,
      };
    },
    decrement(state, action) {
      return {
        ...state,
        count: state.count - action.num,
      };
    },
    add(state, action) {
      console.log(action);
      return {
        ...state,
        list: [
          ...state.list,
          {
            id: new Date().getTime(),
            name: action.value,
          },
        ],
      };
    },
    load2(state, action) {
      return {
        ...state,
        list: action.result,
      };
    },
  },

  // 可以用来监听url
  subscriptions: {
    // setup是一个会自动执行的函数
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/dva') {
          dispatch({
            type: 'load',
          });
        }
      });
    },
  },
};

export default IndexModel;
